from threading import Thread
from time import sleep

from selenium import webdriver

from selenium.webdriver.common.keys  import Keys
class seleniumCrawls():
    def getHeight(el):
        height = el.rect['y'] + el.rect['height']
        return height

if __name__ == '__main__':
    keyword='iphone'
    option = webdriver.ChromeOptions()
    option.add_argument('--headless')
    option.add_argument('--disable-gpu')
    driver = webdriver.Chrome(options=option)

    driver.get("http://www.jd.com")
    #driver.set_window_size(1920  ,1080)
    input_search=driver.find_element_by_id('key')
    input_search.send_keys(keyword)
    input_search.send_keys(Keys.ENTER)
    sleep(2)
    nextPage=''
    while nextPage is not None:
        js="return document.body.scrollHeight"
        ht= driver.execute_script(js)
        print(ht) #通过js返回获取页面滚动高度
        x= 0
        y=200
        while y<ht: # 模拟人类浏览网页每次滚动300高度，同时让所有元素加载完毕每次停顿1秒
            js = "window.scrollTo(0,{})".format(y)
            driver.execute_script(js)
            y=y+300
            sleep(1 )
        products=driver.find_elements_by_class_name('gl-item')
        curpage=driver.find_element_by_class_name("fp-text")
        print(curpage.text)
        print(len(products))
        nextPage=driver.find_element_by_class_name('pn-next')

        nextPage.click()
